/**
 * 
 */
package com.simtek.simplayer;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;

import com.simtek.simplayer.utils.OsDetectUtils;

/**
 * @author Hitech
 * 
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class FullScreenActionActivity extends Activity {

	private boolean	restoreMode;

	public static void hide(Context context) {
		if (instance != null) {
			instance.restoreMode = false;
			instance.finish();
		}
	}

	public static FullScreenActionActivity getInstance() {
		return instance;
	}

	public static void show(Context context, short currentWindowMode) {
		context.startActivity(new Intent(context,
				FullScreenActionActivity.class).putExtra("mode",
				currentWindowMode).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
	}

	private short	prevMode	= VideoPlayerWindow.WINDOW_MODE_FULLSCREEN_WIDTH;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		restoreMode = true;

		if (getIntent() != null) {
			prevMode = getIntent().getShortExtra("mode",
					VideoPlayerWindow.WINDOW_MODE_FULLSCREEN_WIDTH);
		}

		if (OsDetectUtils.hasJellyBean()) {
			setupFullScreen();
		}
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	private void setupFullScreen() {
		final View decorView = getWindow().getDecorView();
		int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
				| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
				| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
				| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
				| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
		;

		if (OsDetectUtils.hasKitKat()) {
			flags = flags | View.SYSTEM_UI_FLAG_IMMERSIVE
					| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
		}
		decorView.setSystemUiVisibility(flags);
	}

	private static FullScreenActionActivity	instance;

	@Override
	protected void onResume() {
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		super.onResume();
		instance = this;
	}

	@Override
	protected void onStop() {
		try {
			if (restoreMode) {
				switch (prevMode) {
				case VideoPlayerWindow.WINDOW_MODE_FULLSCREEN_WIDTH:
					VideoPlayerWindow.showFullWidth(this);
					break;
				case VideoPlayerWindow.WINDOW_MODE_MINIMIZE:
					VideoPlayerWindow.showMinizeWindow(this);
					break;
				}
			}
			finish();
		} catch (Throwable e) {
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		instance = null;
		super.onDestroy();
	}
}
